package com.example.demo.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Result;
import com.example.demo.entity.BdEntry;
import com.example.demo.entity.BdRecords;
import com.example.demo.mapper.EntryMapper;
import com.example.demo.mapper.RecordsMapper;
import com.example.demo.service.RecordsService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("/records")
public class RecordsController extends BaseController{

    @Resource
    RecordsMapper recordsMapper;

    @Resource
    EntryMapper entryMapper;

    @Autowired
    RecordsService recordsService;

    @PostMapping
    public Result<?> save(@RequestBody BdRecords bdRecords) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();

        String jsonString = objectMapper.writeValueAsString(bdRecords);
        Map<String, Object> jsonObject = objectMapper.readValue(jsonString, Map.class);

        // 提取Map对象的键作为KeySet
        Set<String> keySet = jsonObject.keySet();

        // 输出KeySet中的元素
        for (String key : keySet) {
            String value = (String) jsonObject.get(key);
            if ("不合格".equals(value)){
                bdRecords.setUnqualifiedNum(true);
                break;
            }
        }
        recordsMapper.insert(bdRecords);
        return Result.success();
    }

    @PutMapping
    public Result<?> update(@RequestBody BdRecords bdRecords) {
        recordsMapper.updateById(bdRecords);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Integer id) {
        recordsMapper.deleteById(id);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result<?> getById(@PathVariable Integer id) {
        return Result.success(recordsMapper.selectById(id));
    }

    @GetMapping
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String name,
                              @RequestParam(defaultValue = "") String date) {
        LambdaQueryWrapper<BdRecords> wrapper = Wrappers.<BdRecords>lambdaQuery();
        if (StrUtil.isNotBlank(name)) {
            wrapper.like(BdRecords::getName, name);
        }
        if(StrUtil.isNotBlank(date )|| StrUtil.isNotBlank(date)){
            wrapper.and(q -> {
                if(StrUtil.isNotBlank(date)) {
                    q.eq(BdRecords::getDate, date);
                }
            });
        }
        wrapper.orderByDesc(BdRecords::getId);
        Page<BdRecords> recordsPage = recordsMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
        return Result.success(recordsPage);
    }
    @PostMapping("/last")
    public Result<?> getLast(@RequestBody BdRecords bdRecords) {
        LambdaQueryWrapper<BdRecords> wrapper = Wrappers.<BdRecords>lambdaQuery();
        if (StrUtil.isNotBlank(bdRecords.getName())) {
            wrapper.eq(BdRecords::getName, bdRecords.getName());
        }
        wrapper.orderByDesc(BdRecords::getDate);
        wrapper.last("limit 1");
        BdRecords record=recordsMapper.selectOne(wrapper);
        if (record==null){
            Integer activityId= entryMapper.selectIdByName(bdRecords.getName());
            BdEntry resBdEntry =entryMapper.selectByActiveId(activityId);
            return Result.success(resBdEntry);
        }else{
            return Result.success(record);
        }

    }

    /**
     * 导出巡检记录
     *
     * @param id
     * @return null
     */
    @ApiOperation(value = "导出巡检记录", notes = "导出巡检记录")
    @GetMapping(value = "/export/{id}")
    public void export(@PathVariable Integer id, HttpServletResponse response) throws Exception {
        BdRecords bdRecords =recordsMapper.selectById(id);
        recordsService.exportToPdf(bdRecords, response);
    }
}
